/*
 * @Author: 飞越疯人院 353362604@qq.com
 * @Date: 2022-08-26 13:22:24
 * @LastEditors: NaN 353362604@qq.com
 * @LastEditTime: 2023-01-15 09:12:37
 * @FilePath: \reconfiguration-exhibition\src\Login\LoginFunc.jsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { project } from '../Data'
import { Form, Input, Button, notification, Modal } from 'antd'
import { useRequest, useBoolean } from 'ahooks'
import { Http } from '../Api'
import { API_LIST } from '../Api/Api'
import axios from 'axios'
import { UserOutlined } from '@ant-design/icons'

const { hostname } = window.location
const { LoginMethod } = project[hostname]

const NotificationTips = {
    Catch: { message: '服务器出现问题.', description: '网络波动问题,请及时联系管理员了解情况!' },
    Not: { message: '无权进入项目.', description: '该账户没有菜单权限.如有任何问题,请及时联系管理员.' },
    Mod: { message: '无权进入项目.', description: '该账户的密码强度不足,请及时更换密码以防止不必要的意外.' },
}

const { confirm } = Modal

export const LoginSignUpGetUserInfo = ({ token_type, access_token, login_type }, type, LoadingEvent) => {
    sessionStorage.setItem('TOKEN', `${token_type} ${access_token}`)
    axios
        .get(API_LIST()['getMenuWebTree'])
        .then(({ data }) => {
            if (data.length === 0) {
                LoadingEvent.emit()
                notification.error(NotificationTips.Not)
                return false
            }
            sessionStorage.setItem('MENU', JSON.stringify(data))
            axios.get(API_LIST()['getUserInfo']).then(({ data: userInfo }) => {
                const { hasValidPassword, userName, userRoles } = userInfo
                if (hasValidPassword === 'no' && type === 1) {
                    LoadingEvent.emit(1)
                    notification.error(NotificationTips.Mod)
                    return false
                }

                if (userInfo.menuUuid) sessionStorage.setItem('OpenUuid', JSON.stringify(userInfo.menuUuid))
                sessionStorage.setItem('UserInfo', JSON.stringify(userInfo))

                axios.get(API_LIST()['getClientData']).then(({ data }) => {
                    const { tag, clientData } = data
                    localStorage.setItem('ClientTag', tag)
                    localStorage.setItem('ClientData', JSON.stringify(clientData))
                    axios
                        .get(`${API_LIST()['getJsonInfoByUuid']}?uuid=theme${Object.keys(clientData.project)[0]}`, {
                            headers: { Authorization: `${token_type} ${access_token}` },
                        })
                        .then(({ data }) => {
                            sessionStorage.setItem('temporaryData', JSON.stringify(data))
                            signUpSuccess({
                                role: clientData.role[userRoles[0]],
                                user: userName,
                                type: login_type ? login_type : undefined,
                                userInfo,
                            })
                        })
                })
            })
        })
        .catch(() => {
            LoadingEvent.emit()
            // notification.error(NotificationTips.Catch)
        })
}

// 登录成功 , 判断进入前后端项目
const signUpSuccess = ({ role = '编外人士', user, type, userInfo }) => {
    if (type)
        window.location.href =
            Number(type) === 0 ? `${window.location.origin}/Front` : `${window.location.origin}/Admin`
    else {
        if (LoginMethod) {
            window.location.href = `${window.location.origin}/${LoginMethod}`
        } else {
            const { userOrganizationIdentityLevels } = userInfo
            let url = window.location.origin + '/Front'

            if (hostname === 'jtgj.ljkjkf.com')
                url = userOrganizationIdentityLevels.includes('9')
                    ? window.location.origin + '/Front'
                    : window.location.origin + '/Front/Page/OneOne'

            confirm({
                icon: <UserOutlined />,
                className: 'SignUpOk',
                centered: true,
                keyboard: false,
                maskClosable: false,
                title: `欢迎 ${role} - ${user}`,
                content: '请选择进入位置',
                okText: '后台',
                cancelText: '大屏',
                onOk: () => (window.location.href = `${window.location.origin}/Admin`),
                onCancel: () => (window.location.href = url),
            })
        }
    }
}

export const ModifyPassword = ({ Off, userInfo }) => {
    const { runAsync } = useRequest(Http, { manual: true })
    const [Loading, { setTrue, setFalse }] = useBoolean(false)
    return (
        <Modal className="ModalBox" title="修改密码" footer={null} open={true} centered destroyOnClose onCancel={Off}>
            <div className="NewPassword">密码六位以上,并由大写字母、小写字母和数字组成</div>
            <Form
                layout="vertical"
                autoComplete="off"
                initialValues={{ userName: userInfo.username, oldPassword: userInfo.password }}
                onFinish={e => {
                    setTrue()
                    const { userName, oldPassword, newPassword } = e
                    runAsync({ url: 'posUserChangePassword', data: { userName, oldPassword, newPassword } })
                        .then(() => {
                            notification.success({ message: `密码修改成功!`, duration: 2 })
                            Off()
                        })
                        .catch(setFalse)
                }}
            >
                <Form.Item name="userName" label="登录账户" rules={[{ required: true, message: '必须填写登录用户!' }]}>
                    <Input placeholder="请输入登录账户" />
                </Form.Item>

                <Form.Item
                    name="oldPassword"
                    label="原登录密码"
                    rules={[{ required: true, message: '必须填写原登录密码!' }]}
                >
                    <Input.Password placeholder="请输入登录账户" />
                </Form.Item>

                <Form.Item
                    name="newPassword"
                    label="新密码"
                    rules={[
                        { required: true, message: '必须填写新登录密码' },
                        () => ({
                            validator(_, value) {
                                const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{6,}$/
                                if (regex.test(value)) return Promise.resolve()
                                return Promise.reject(new Error('密码六位以上,并由大写字母、小写字母和数字组成'))
                            },
                        }),
                    ]}
                >
                    <Input.Password placeholder="请输入新的登录密码" />
                </Form.Item>

                <Form.Item
                    name="confirm"
                    label="重复密码"
                    dependencies={['newPassword']}
                    rules={[
                        { required: true, message: '必须验证新密码' },
                        ({ getFieldValue }) => ({
                            validator(_, value) {
                                if (!value || getFieldValue('newPassword') === value) return Promise.resolve()
                                return Promise.reject(new Error('您输入的两个密码不匹配！'))
                            },
                        }),
                    ]}
                >
                    <Input.Password placeholder="请确认新的登录密码" />
                </Form.Item>

                <Form.Item className="SignUpBtn">
                    <Button block type="primary" htmlType="submit" loading={Loading}>
                        {Loading ? '提交中...' : '提交'}
                    </Button>
                </Form.Item>
            </Form>
        </Modal>
    )
}
